//
//  SearchGoodsViewController.m
//  Wujin
//
//  Created by cz on 2016/12/9.
//  Copyright © 2016年 dong. All rights reserved.
//

#import "SearchGoodsViewController.h"
#import "GoodCollectionViewCell.h"
#import "GoodsDetail.h"

@interface SearchGoodsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *goodList;


@end

@implementation SearchGoodsViewController
static NSString * const goodResueId = @"goodCell";

- (NSMutableArray *)goodList {
    if (!_goodList) {
        _goodList = [NSMutableArray array];
    }
    return _goodList;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(100, 100);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        
        self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, SCREENBOUNDS.width, SCREENBOUNDS.height) collectionViewLayout:layout];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        self.collectionView.backgroundColor = [UIColor whiteColor];
        
        //注册cell
        [self.collectionView registerNib:[UINib nibWithNibName:@"GoodCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:goodResueId];
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置UI
    [self setupUI];
}

- (void)setupUI {
    
    self.title = @"搜索结果";
    //设置collectionView
    [self.view addSubview:self.collectionView];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    //给个返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backClick)];
    //设置刷新控件
    [self setupRefreshControl];
    //自动刷新控件
    [self.collectionView.mj_header beginRefreshing];
}

/**
 设置刷新控件
 */
- (void)setupRefreshControl {
    //添加下拉刷新控件
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewShopData)];
    //添加上拉刷新控件
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreShopData)];
    
}


#pragma mark -- collectionView的代理与数据源方法
//组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}
//行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.goodList.count;
}

//设置每个组的边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
    
}

//设置每个item的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat width = SCREENBOUNDS.width * 0.5;
    
    return CGSizeMake(width, width * 1.3);
}

/**
 设置collectionViewcell
 */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GoodCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:goodResueId forIndexPath:indexPath];
    cell.goodsList = self.goodList[indexPath.row];
    return cell;
}

/**
 点击cell调用,跳转到商品详情
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    DLog(@"%ld",(long)indexPath.row);
    GoodsDetail *detail = [UIViewController storyboardWithName:@"Home" storyboardID:@"goodsdetail"];
    GoodsModel *model = _goodList[indexPath.row];
    detail.goodsID = model.gds_id;
    [self pushViewController:detail];
    
}

/**
 加载新的商品数据
 */
- (void)loadNewShopData {
    //一上拉拉，就停止下拉刷新
    [self.collectionView.mj_footer endRefreshing];
    //只要一上拉刷新，就把下拉刷新请求的起始页数重置
    i = 2;
    
    DLog(@"上拉%ld",(long)i);
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"page"] = @(1);
    dict[@"limit"] = @10;
    
    if (self.keyword != nil) {
        dict[@"keyword"] = F(@"%@", self.keyword);
    }else{
        dict[@"gc_id"] = F(@"%@", self.gc_id);
    }
        
    NSString *url = F(@"%@Index/goodsList", BASEURL);
    
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        
        NSDictionary *dict = responseObject[@"data"];
        
        if (dict.count != 0) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                if ([responseObject[@"flag"] intValue] == 1) {
                    NSArray *array = dict[@"goods"];
                    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, array.count)];
                    NSMutableArray *tempA = [NSMutableArray array];
                    self.goodList = nil;
                    for (NSDictionary *goodsDict in array) {
                        GoodsModel *goodsList = [GoodsModel yy_modelWithDictionary:goodsDict];
                        [tempA addObject:goodsList];
                    }
                    [self.goodList insertObjects:tempA atIndexes:indexSet];
                    [self.collectionView reloadData];
                    //停止刷新
                    [self.collectionView.mj_header endRefreshing];
                }else{
    
                    DLog(@"没有请求到数据");
                }
            }
        }else{
            DLog(@"没有该商品");
            //停止刷新
            [self.collectionView.mj_header endRefreshing];
            [MRHud show];
            [MRHud dismissWithFailure:@"没有找到该商品"];
            [self backClick];
        }
    }];
}

/**
 加载更多商品数据
 */

//下拉加载更多的起始页数
static NSInteger i = 2;
//下拉刷新的上限
static NSInteger maxI = 10;

- (void)loadMoreShopData {
    
    //一下拉，就停止上拉刷新
    [self.collectionView.mj_header endRefreshing];
    
    if (i > maxI) {
        
        [self.collectionView.mj_footer endRefreshing];
        [MRHud show];
        [MRHud dismissWithFailure:@"没有更多商品了"];
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"limit"] = @10;
    
    
    dict[@"page"] = F(@"%ld", (long)i);
    
    if (self.keyword != nil) {
        dict[@"keyword"] = F(@"%@", self.keyword);
    }else{
        dict[@"gc_id"] = F(@"%@", self.gc_id);
    }
    
    NSString *url = F(@"%@Index/goodsList", BASEURL);
    
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        NSDictionary *dict = responseObject[@"data"];
        if (([responseObject[@"flag"] intValue] == 1) && dict.count != 0) {
            
            i++;
            NSArray *array = dict[@"goods"];
            
            NSMutableArray *tempA = [NSMutableArray array];
            
            for (NSDictionary *goodsDict in array) {
                GoodsModel *goodsList = [GoodsModel yy_modelWithDictionary:goodsDict];
                [tempA addObject:goodsList];
            }
            [self.goodList addObjectsFromArray:tempA];
            
            [self.collectionView reloadData];
            //停止刷新
            [self.collectionView.mj_footer endRefreshing];
        }else{
            DLog(@"没有请求到数据");
            [self.collectionView.mj_footer endRefreshing];
            
            [MRHud show];
            [MRHud dismissWithFailure:@"没有更多商品了"];
        }
    }];
}

- (void)backClick{
    //点击返回隐藏模态窗口
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
